<!--
 * @Description: 用于展示消息模板
 * @Version: 1.0
 * @Autor: chen_yt
 * @Date: 2020-11-02 17:15:31
 * @LastEditors: chen_yt
 * @LastEditTime: 2022-07-12 14:29:28
-->
<template>
  <div
    class="Template"
    style="min-width: 716px; height: 100%"
  >
    <fks-query-page
      ref="templateTable"
      v-loading="tableLoading"
      :data="tableData"
      :page="false"
      :element-loading-text="LANG.LOADING"
      :table-name="LANG.STC_MSG_TEMPLATE"
      @sort-change="sortHandle"
    >
      <template slot="singleSearch">
        <div class="single-searchBox">
          <fks-radio-group
            v-model="msgSendType"
            size="medium"
            class="single-searchBox-item"
            style="width: auto"
            @change="handleClick"
          >
            <fks-radio-button
              v-for="type in msgSendTypeList"
              :key="type.code"
              :label="type.code"
            >
              {{ type[$lang] }}
            </fks-radio-button>
          </fks-radio-group>
          <fks-input
            v-model="keywords"
            size
            class="single-searchBox-item"
            :placeholder="LANG.INPUT_TEMPLATE_NAME"
            maxlength="50"
            clearable
            @clear="search"
            @keyup.native.enter="search"
          >
            <fks-button
              slot="append"
              icon="fks-icon-search"
              @click="search"
            />
          </fks-input>
          <fks-button
            v-permission="['msgTemplate:add']"
            type="primary"
            icon="fks-icon-plus"
            @click="addTemplate"
          >
            {{ LANG.ADD }}
          </fks-button>
        </div>
      </template>

      <!-- 使用V-IF 为防止表头乱飞，每个column加上key -->
      <fks-table-column
        key="index"
        label="#"
        width="55"
        header-align="center"
        align="center"
      >
        <template slot-scope="scope">
          <span style="cursor: pointer !important">
            <!-- {{ (pageNo - 1) * pageSize + scope.$index + 1 }} -->
            {{ scope.$index + 1 }}
          </span>
        </template>
      </fks-table-column>
      <fks-table-column
        key="templateName"
        sortable="custom"
        :label="LANG.NAME"
        min-width="120px"
        prop="templateName"
        header-align="center"
        align="left"
        is-link
        @link="showTemplate"
      />

      <!-- 站内信参数展示 -->
      <template v-if="msgType == 0">
        <fks-table-column
          key="destination"
          :label="LANG.LISTENER_PORT"
          prop="destination"
          min-width="120px"
          header-align="center"
          align="left"
        />
      </template>

      <!-- 短信参数展示 -->
      <template v-if="msgType != 0">
        <fks-table-column
          key="serverId"
          :label="LANG.SERVICE_NAME"
          :render-header="roleSelect"
          prop="serverId"
          min-width="120px"
          header-align="center"
          align="left"
        >
          <template slot-scope="scope">
            <span>
              {{ getServerNameById(scope.row.serverId) }}
            </span>
          </template>
        </fks-table-column>
        <fks-table-column
          v-if="msgType == 1"
          key="serverTemplateId"
          :label="LANG.THIRD_TEMPLATE_ID"
          prop="serverTemplateId"
          min-width="120px"
          header-align="center"
          align="left"
        />
      </template>

      <!--邮件参数展示 -->
      <template v-if="msgType == 2">
        <fks-table-column
          key="subject"
          :label="LANG.SUBJECT"
          prop="subject"
          min-width="200px"
          header-align="center"
          align="left"
        />
      </template>
      <fks-table-column
        :label="LANG.TEMPLATE_ID"
        prop="id"
        min-width="120px"
        class="templateId"
        header-align="center"
      >
        <template slot-scope="scope">
          <span>
            {{ scope.row.id }}
          </span>
          <fks-button
            v-clipboard:copy="scope.row.id"
            v-clipboard:success="onCopy"
            v-clipboard:error="onError"
            class="copyButton"
            icon="fks-icon-copy"
          />
        </template>
      </fks-table-column>

      <fks-table-column
        :label="LANG.UPDATE_BY"
        prop="updateBy"
        min-width="50px"
        header-align="center"
      />
      <fks-table-column
        sortable="custom"
        :label="LANG.UPDATE_DATE"
        prop="updateDate"
        min-width="100px"
        header-align="center"
      />
      <fks-table-column
        key="operation"
        :label="LANG.OPERATION"
        width="180"
        align="left"
      >
        <template slot-scope="scope">
          <div>
            <fks-button
              v-permission="['msgTemplate:edit']"
              type="text"
              @click="editTemplate(scope.row)"
            >
              {{ LANG.EDIT }}
            </fks-button>
            <fks-button
              v-permission="['msgTemplate:test']"
              type="text"
              @click="testTemplate(scope.row)"
            >
              {{ LANG.TEST }}
            </fks-button>

            <!-- <fks-popover
              style="margin-right: 10px; margin-left: 10px"
              placement="bottom"
              trigger="click"
            >
              <span
                text-align="left"
                style="float: left; margin-bottom: 8px; font-size: 18px"
                >{{ LANG.TEMPLATE_ID }}</span
              >
              <fks-input v-model="scope.row.id" readonly>
                <fks-tooltip
                  slot="append"
                  class="item"
                  effect="dark"
                  :content="LANG.COPY_ID"
                  placement="bottom"
                >
                  <fks-button
                    v-clipboard:copy="scope.row.id"
                    v-clipboard:success="onCopy"
                    v-clipboard:error="onError"
                    icon="fks-icon-copy"
                  />
                </fks-tooltip>
              </fks-input>
              <fks-button
                slot="reference"
                v-permission="['msgTemplate:copy']"
                type="text"
              >
                {{ LANG.COPY }}
              </fks-button>
            </fks-popover> -->
            <fks-button
              v-permission="['msgTemplate:delete']"
              type="text"
              style="color: #ff4d4f"
              @click="delTemplate(scope.row)"
            >
              {{ LANG.DELETE }}
            </fks-button>
          </div>
        </template>
      </fks-table-column>
    </fks-query-page>

    <div class="dialogs">
      <componet
        :is="msgType == 1 ? 'Sms' : 'msg-and-email'"
        :visible="visible_add_template"
        :template-id="template_id"
        :operate-type="operate_type"
        :msg-send-type="msgSendType"
        :server-list="serverConfigList"
        @close="closeAddTemplate"
        @submit="submitAddTemplate"
      />
      <msg-post
        :visible="visible_test"
        :template-id="template_id"
        @close="closeTestTemplate"
      />
    </div>
  </div>
</template>

<script>
import VueClipboard from 'vue-clipboard2'
import Vue from 'vue'
import { getServerConfig, getMsgTemplateList } from './api'
import { delTemplateById } from './api'
import MsgAndEmail from './components/MsgAndEmail/index'
import Sms from './components/Sms/index'
import MsgPost from './components/MsgPost/index'
import { ENUM } from '@/store/State/stateTypes'
import mix from '@/mixins/module'
import SaasMix from '@/saas/mixins'

Vue.use(VueClipboard)

export default {
  name: 'MessageTemplate',
  components: {
    MsgAndEmail,
    MsgPost,
    Sms
  },
  mixins: [mix, SaasMix],
  data() {
    return {
      currentServer: '',
      msgSendType: '',
      sort: '',
      columnName: '',
      serverConfigList: [],
      pageNo: 1,
      pageSize: 100,
      total: 0,
      tableLoading: false,
      visible_add_template: false,
      visible_test: false,
      keywords: '',
      operate_type: 'new',
      tableData: [], //table展示用数据
      template_id: '',
      templateList: [] //获取到的分类目录数据
    }
  },
  computed: {
    msgType() {
      if (this.msgSendType) return this.msgSendType
      return 0
    },
    msgSendTypeList() {
      return this.$store.state[ENUM].msgSendType || []
    },
    serverList() {
      return [
        ...[{ serverName: this.LANG.ALL_SERVER, id: '' }],
        ...this.serverConfigList
      ]
    }
  },
  watch: {
    msgSendTypeList(val) {
      this.msgSendType = val[0].code
      this.getList()
      this.initData()
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    /**
     * @description: 表头渲染方法
     */
    roleSelect(h, { column, $index }) {
      return (
        <div>
          <FksSelect
            value={this.currentServer}
            onchange={(val) => {
              this.currentServer = val
              this.getList()
            }}
            size="small"
            style="width:100%"
          >
            {this.serverList.map((item) => {
              return (
                <FksOption
                  value={item.id}
                  label={item.serverName ? item.serverName : item.id}
                ></FksOption>
              )
            })}
          </FksSelect>
        </div>
      )
    },

    /**
     * @description: 根据服务器id获得名称
     */
    getServerNameById(id) {
      for (let item of this.serverConfigList) {
        if (item.id == id) return item.serverName ? item.serverName : id
      }
      return id
    },

    /**
     * @description: 排序响应
     * @param {prop,order} sort
     */
    sortHandle(sort) {
      this.columnName = sort.prop
      if (!sort.order) {
        this.sort = ''
        this.columnName = ''
      } else {
        this.sort = sort.order === 'ascending' ? 'asc' : 'desc'
      }
      this.search()
    },

    /**
     * @description: 复制模板ID功能回调
     */
    onCopy(e) {
      this.$message({
        message: this.LANG.SUCCESS_COPY_TEMPLATEID,
        type: 'success'
      })
    },
    onError(e) {
      this.$message({
        message: this.LANG.ERROR_COPY_TEMPLATEID,
        type: 'error'
      })
    },

    /**
     * @description: 删除消息模板
     *
     */
    delTemplate(row) {
      this.$confirm(this.LANG.DELETE_CONFIRM, this.LANG.TIPS, {
        confirmButtonText: this.LANG.DELETE,
        cancelButtonText: this.LANG.CANCEL,
        confirmButtonClass: 'fks-button--danger',
        deleteMode: true,
        type: 'warning'
      })
        .then(() => {
          this.delTemplateById(row.id)
        })
        .catch(() => {})
    },
    delTemplateById(id) {
      delTemplateById(id)
        .then((res) => {
          if (res.status) {
            this.$message({
              type: 'success',
              message: this.LANG.DELETE_SUCCESS
            })
            this.search()
          }
        })
        .catch(() => {})
    },

    /**
     * @description:获得templateList的展示数据
     */

    getList: async function () {
      this.tableLoading = true
      await this.getMsgTemplateList()
      this.tableData = [...this.templateList]
      this.tableLoading = false
    },
    @permission('msgTemplate:query')
    getMsgTemplateList() {
      let temp = {
        serverId: this.currentServer,
        currentPage: this.pageNo,
        pageSize: this.pageSize,
        templateName: this.keywords,
        supportedMsgSendTypes: this.msgSendType,
        columnName: this.columnName,
        sort: this.sort
      }
      return getMsgTemplateList(temp)
        .then((res) => {
          if (res.status) {
            this.templateList = res.data.list ? res.data.list : []
            this.total = res.data.total
            for (let item of this.templateList) {
              if (!item.templateParamDefaultValue) continue
              let paramList = JSON.parse(item.templateParamDefaultValue)
              if (this.msgType == 0) {
                this.addAttr(item, paramList, 'destination')
              }
              if (this.msgType != 0) {
                this.addAttr(item, paramList, 'serverId')
                if (this.msgType == 1) {
                  this.addAttr(item, paramList, 'serverTemplateId')
                }
              }
              if (this.msgType == 2) {
                this.addAttr(item, paramList, 'subject')
              }
            }
          }
        })
        .catch(() => {
          this.templateList = []
          this.total = 0
        })
    },

    addAttr(obj, paramList, attrName) {
      obj[attrName] = paramList[attrName] ? paramList[attrName] : ''
    },

    /**
     * @description: 搜索框
     */
    search() {
      this.pageNo = 1
      this.getList()
    },

    initData() {
      //获取短信服务器信息
      getServerConfig()
        .then((res) => {
          if (res.status) {
            switch (this.msgSendType) {
              case '1': {
                this.serverConfigList = res.data.smsServerConfig ?? []
                break
              }
              case '2': {
                this.serverConfigList = res.data.mailServerConfig ?? []
                break
              }
              case '3': {
                this.serverConfigList = res.data.jpushServerConfig ?? []
                break
              }
              case '4': {
                this.serverConfigList = res.data.dingTalkServerConfig ?? []
                break
              }
              case '5': {
                this.serverConfigList = res.data.qywxServerConfig ?? []
                break
              }
              case '7': {
                this.serverConfigList = res.data.larkServerConfig ?? []
                break
              }
            }
          }
        })
        .catch(() => {})
      if (!this.msgSendType) {
        if (this.msgSendTypeList.length > 0) {
          this.msgSendType = this.msgSendTypeList[0].code
          this.getList()
        } else {
          //可能还没导入enum，临时先用这个
          this.msgSendType = '0'
          this.getList()
        }
      }
    },

    /**
     * @description: 按钮相关代码
     */
    addTemplate() {
      this.operate_type = 'new'
      this.openAddTemplate()
    },
    editTemplate(row) {
      this.operate_type = 'edit'
      this.template_id = row.id
      this.openAddTemplate()
    },
    showTemplate({ row }) {
      this.operate_type = 'show'
      this.template_id = row.id
      this.openAddTemplate()
    },

    /**
     * @description: 模板测试
     */
    testTemplate(row) {
      this.template_id = row.id
      this.openTestTemplate()
    },

    /**
     * @description: 模板编辑弹窗控制相关代码
     */
    openAddTemplate() {
      this.visible_add_template = true
    },
    closeAddTemplate() {
      this.visible_add_template = false
      this.template_id = ''
      this.operate_type = 'new'
    },
    submitAddTemplate() {
      this.closeAddTemplate()
      this.search()
    },

    /**
     * @description: 模板测试弹窗控制相关代码
     */
    openTestTemplate() {
      this.visible_test = true
    },
    closeTestTemplate() {
      this.visible_test = false
    },

    clearSearch() {
      this.currentServer = ''
      this.keywords = ''
      this.columnName = ''
      this.sort = ''
      this.$refs.templateTable.clearSort()
    },
    /**
     * @description: 切换Tab
     */
    handleClick(val) {
      this.msgSendType = val
      this.clearSearch()
      this.getList()
      this.initData()
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .fks-table th > .cell .fks-input--small .fks-input__inner {
  border: none;
  text-align: center;
  background-color: transparent;
}

::v-deep .fks-select .fks-input .fks-select__caret {
  margin-top: -0.5px;
}

::v-deep .fks-table .fks-input--suffix .fks-input__inner {
  padding-left: 30px !important;
}
.copyButton {
  width: 20px;
  height: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0px;
  margin-left: 4px;
  background: rgba(255, 255, 255, 0.5);
  border: none;
}
::v-deep .fks-table .cell {
  display: flex !important;
  align-items: center;
  justify-content: center;
}
</style>
